var tree_cluster_selections = new Array();

var old_scale;
var in_select = false;
var selected = new Array();
var azap;
var NL = /\n/.source;

var activeannot = new Array();
var availcolors = new Array();
availcolors[0] = "black";
availcolors[1] = "red";
availcolors[2] = "green";
availcolors[3] = "blue";
availcolors[4] = "yellow";
availcolors[5] = "orange";

function save_cluster_as_dataset () {
  seeobj ( evt );
}

function export_svg () {
  //  alert ( "exporting " + svg_filename );
  browserEval ( "document.location.href = " + svg_filename );
}

function on_zoom () {
  if ( window.svgDocument == null )
    svgDocument = e.target.ownerDocument;

  TooltipZoomControl ();

  if ( svgDocument.rootElement.currentScale != 1 ) {
    var k = svgDocument.rootElement.currentScale / old_scale;
    browserEval ( "if ( document.getElementById ('svg_vis') ) { document.getElementById('svg_vis').height *= " + k + ";document.getElementById('svg_vis').width  *= " + k + "}" );
  }
}

function make_menus ( menu_name ) {
  var newMenuRoot = parseXML ( printNode ( document.getElementById ( menu_name ) ), contextMenu );
  contextMenu.replaceChild ( newMenuRoot, contextMenu.firstChild ) 
}

function setActiveAnnot ( annot_set_id, id ) {
  var lastactive = document.getElementById ( 'annot_' + annot_set_id + "_" + activeannot[annot_set_id] );
  if ( lastactive )
    lastactive.getStyle().setProperty ( "display", "none" );

  var annot = document.getElementById ( 'annot_' + annot_set_id + "_" + id );
  if ( annot )
    annot.getStyle().setProperty ( "display", "visible" );

  activeannot[annot_set_id] = id;
}

function selectRange ( evt ) {
  var rect = evt.target;
  if ( !in_select ) { 
    in_select = true;
    startSelect ( rect );
  } else {
    in_select = false;
    var sel_conds = finishSelect ( rect );

    browserEval ( "if ( top.document.mainfrm.subselect_column_headers___c_15_s_1 ) top.document.mainfrm.subselect_column_headers___c_15_s_1.value='" + sel_conds + "'" );
  }
}

function toggle_display ( obj_id ) {
  if ( !obj_id ) return;

  var obj = document.getElementById ( obj_id );

  if ( obj.getStyle().getPropertyValue ( "display" ) == "none" ) {
    obj.getStyle().setProperty ( "display", "visible" );
  } else {
    obj.getStyle().setProperty ( "display", "none" );
  }
}

function seeobj ( e ) {
  var s = "";
  for ( o in e ) {
    //    if ( typeof ( e[o] ) == "object" )
      s += o + ": " + e[o] + "\n";
  }
  alert (s);
}

function contSelect ( evt ) {
  if ( !in_select ) return;
  var rect = evt.target;	
  rect.getStyle().setProperty ( "fill", "fuchsia" );
  for ( r in selected ) {
    if ( rect == selected[r] )
      return;
  }
  selected[selected.length] = rect;
}
          
function startSelect ( rect ) {
  // reset
  for ( r in selected ) {
    selected[r].getStyle().setProperty ( "fill", "pink" );
  }
  selected = new Array();
          
  // select new starting one
  rect.getStyle().setProperty ( "fill", "purple" );
  selected[0] = rect;
}

function finishSelect ( rect ) {
  rect.getStyle().setProperty ( "fill", "orange");
          
  var s = "";
  for ( r in selected ) {
    s += get_annot ( "h", selected[r].getAttribute("hook_id") ) + NL;
  }

  return s;
}

function get_annot ( hook_type, id ) {
  if ( hook_type == "h" ) {
    var hooks = document.getElementsByTagName ( "hhook" );
    for ( var i = 0; i < hooks.length; i++ ) {
      if ( hooks.item(i).getAttribute ( "hook_id" ) == id ) 
	return hooks.item(i).getAttribute ( "annot" );
    }
  } else {  var top = evt.target;

    var hooks = document.getElementsByTagName ( "vhook" );
    for ( var i = 0; i < hooks.length; i++ ) {
      if ( hooks.item(i).getAttribute ( "hook_id" ) == id ) 
	return hooks.item(i).getAttribute ( "annot" );
    }
  }
}

function messages_use_pick_color ( result, data, num_w ) {
  shape = document.getElementById ( num_w );

  if ( result==true ) {
    shape.getStyle().setProperty ( "fill", data );	
  } else {
    shape.parentNode.removeChild ( shape );
  }
}

function prompt ( evt, message, num ) {
  add_prompt ( html_href + "/static/images/prompt.svg", "messages", message, num );
  // TODO: Position message_obj in the center of the screen.
  //  message_obj = document.getElementById ( "messages" );

  //  var mx = evt.getClientX() - 150;
  //  var my = evt.getClientY() - 80;

  //  var transform = "translate(" + mx + "," + my  + ")";
  //  message_obj.setAttribute ( "transform", transform );
}

function messages_use_prompt ( result, data, ids ) {
  var ids_arr = ids.split ( "," );

  tree_cluster_selections[ids_arr[0]][ids_arr[1]][2] = data;

  set_cluster_name ( ids_arr[2], data );
}

function set_cluster_name ( cluster_id, data ) {
  var shape = svgDocument.getElementById ( cluster_id );
  var cluster_name_id = "N" + cluster_id;
  var clust_name = svgDocument.getElementById ( cluster_name_id );

  if ( !clust_name ) {
    clust_name = svgDocument.createElement ( "text" );
  
    clust_name.setAttribute ( "id", cluster_name_id );
    clust_name.appendChild ( svgDocument.createTextNode ( data ) );

    clust_name.setAttribute ( "x", shape.getAttribute ( "x" ) );
    clust_name.setAttribute ( "y", parseInt(shape.getAttribute ( "y" )) - 7 );

    shape.parentNode.appendChild ( clust_name );
  } else {
    clust_name.replaceChild (  svgDocument.createTextNode ( data ), clust_name.firstChild );
  }  
}

function select_subtree ( tree_id, leftmost, rightmost, name ) {
  var top_id = "T:" + tree_id + ":" + leftmost + ":" + rightmost;
  var top = document.getElementById (top_id);

  var left  = document.getElementById ( tree_id + ":" + leftmost  );
  var right = document.getElementById ( tree_id + ":" + rightmost );

  if ( !left ) return;

  if ( window.svgDocument == null )
    svgDocument = evt.target.ownerDocument;
  
  var lx = left.getAttribute ( "cx" );
  var ly = left.getAttribute ( "cy" );

  var rx = right.getAttribute ( "cx" );
  var ry = right.getAttribute ( "cy" );

  var tx = top.getAttribute ( "cx" );
  var ty = top.getAttribute ( "cy" );

  var w = rx - lx;
  var h = ly - ty;

  var tree = document.getElementById ( tree_id );

  var shape = document.getElementById ( "C:" + tree_id + ":" + leftmost + ":" + rightmost );

  if ( shape ) {
//    if ( !evt.shiftKey ) {
      clust_name = document.getElementById ( "N" + shape.id );
      if ( clust_name )
	clust_name.parentNode.removeChild ( clust_name );
      shape.parentNode.removeChild ( shape );
      for ( cluster_sel in tree_cluster_selections[tree_id] ) {
	if ( tree_cluster_selections[tree_id][cluster_sel][0] == top.getAttribute("lh") &&
	     tree_cluster_selections[tree_id][cluster_sel][1] == top.getAttribute("rh") ) {
	  tree_cluster_selections[tree_id].splice(cluster_sel, 1);
	  break;
	}
      }
//    }
  } else {
    shape = svgDocument.createElementNS(svgns, "rect");
    shape.setAttributeNS ( null, "id", "C:" + tree_id + ":" + leftmost + ":" + rightmost );
    shape.setAttributeNS ( null, "x", lx);
    shape.setAttributeNS ( null, "y", ly - h );
    shape.setAttributeNS ( null, "rx", 4 );
    shape.setAttributeNS ( null, "ry", 4 );
    shape.setAttributeNS ( null, "width", w );
    shape.setAttributeNS ( null, "height", h );
    shape.setAttributeNS ( null, "fill", "black" );
    shape.setAttributeNS ( null, "fill-opacity", "0.2");
    shape.setAttributeNS ( null, "stroke", "red" );
    shape.setAttributeNS ( null, "stroke-width", "3" );

    tree.insertBefore ( shape, tree.firstChild );

    if ( !tree_cluster_selections[tree_id] )
      tree_cluster_selections[tree_id] = new Array();
    
    tree_cluster_selections[tree_id][tree_cluster_selections[tree_id].length] = new Array ( top.getAttribute("lh"), top.getAttribute("rh"), name, leftmost, rightmost );
    if ( name )
      set_cluster_name (  "C:" + tree_id + ":" + leftmost + ":" + rightmost, name );
  }

  // only show prompt for name if one is not already on the screen (test 'messages' for child nodes)
  if ( evt && evt.shiftKey && !svgDocument.getElementById ( "messages" ).hasChildNodes() ) {
    var cur_name = "";
    for ( cluster_sel in tree_cluster_selections[tree_id] ) {
      if ( tree_cluster_selections[tree_id][cluster_sel][0] == top.getAttribute("lh") &&
	   tree_cluster_selections[tree_id][cluster_sel][1] == top.getAttribute("rh") ) {
	cur_name = tree_cluster_selections[tree_id][cluster_sel][2];
	break;
      }
    }
    var prompt_message = "Name this sub-tree\n";
    if ( cur_name == null )
      prompt_message += "- no name given -\n";
    else
      prompt_message += "(" + cur_name + ")\n";
    
    prompt_message += "\n";

    prompt ( evt, prompt_message, tree_id + "," + cluster_sel + "," + shape.id );
  }
}

function save_clusters ( tree_id ) {
  getURL ( cgi_href + "/ep_save_clusters.pl?clusters=" + clusters(tree_cluster_selections[tree_id]) + '&tree_id=' + tree_id, clusters_saved );
}

function clusters ( sel ) {
  var c = sel.join (":");

  return c;
}

function load_saved_clusters ( urlRequestStatus ) {
  if ( urlRequestStatus.success ) {
    var data = urlRequestStatus.content.split ( ':' );
    var tree_id = data[0];

    for ( var i = 1; i < data.length; i++ ) {
      var cluster = data[i].split (',');
      select_subtree ( tree_id, cluster[3], cluster[4], cluster[2] );
    }

    //    alert ( urlRequestStatus.content );
  }
}

function clusters_saved ( urlRequestStatus ) { 
  if ( urlRequestStatus.success ) {
    browserEval ( "alert('Clusters saved!');" );
  }
}

function get_avail_tree_select_color () {
  for ( i = 0; i < availcolors.length; i++ ) {
    if ( availcolors[i] != 0 ) {
      color = availcolors[i];
      availcolors[i] = 0;
      return color;
    }
  }

  return -1;
}

function sselect_subtree ( tree_id, lh, rh, below ) {
  var circ = evt.target;

  var highlight = "red";

  if ( ( below == 1 ) || ( circ.getAttribute ( "selected" ) == 0  ) ) {
    var pl = document.getElementById ( tree_id + ":" + lh + ":" + rh );

    pl.getStyle().setProperty ( "stroke", highlight );
    pl.getStyle().setProperty ( "stroke-width", "2" );
    
    var lh1 = pl.getAttribute ( "lh1" );
    var rh1 = pl.getAttribute ( "rh1" );
    
    var lh2 = pl.getAttribute ( "lh2" );
    var rh2 = pl.getAttribute ( "rh2" );
    
    if ( lh1 != 0 && rh1 != 0 )
      select_subtree ( tree_id, lh1, rh1, 1 );
    
    if ( lh2 != 0 && rh2 != 0 )
      select_subtree ( tree_id, lh2, rh2, 1 );

    circ.setAttribute ( "selected", 1 );
  } else {
    unselect_subtree ( tree_id, lh, rh );
    circ.setAttribute ( "selected", 0 );
  }
}

function unselect_subtree ( tree_id, lh, rh ) {
  var pl = document.getElementById ( tree_id + ":" + lh + ":" + rh );

  pl.getStyle().setProperty ( "stroke", "black" );
  pl.getStyle().setProperty ( "stroke-width", "0.7" );
    
  var lh1 = pl.getAttribute ( "lh1" );
  var rh1 = pl.getAttribute ( "rh1" );
  
  var lh2 = pl.getAttribute ( "lh2" );
  var rh2 = pl.getAttribute ( "rh2" );
  
  if ( lh1 != 0 && rh1 != 0 )
    unselect_subtree ( tree_id, lh1, rh1 );
  
  if ( lh2 != 0 && rh2 != 0 )
    unselect_subtree ( tree_id, lh2, rh2 );
}

function changeColor(evt) {
  var rect = evt.target;
          
  if ( rect.getStyle().getPropertyValue ( "fill" ) == "purple" ) 
    rect.getStyle().setProperty ( "fill", "pink");
  else
    rect.getStyle().setProperty ( "fill", "purple");	
}

function zoomer(k) {
  if ( window.svgDocument == null )
    svgDocument = e.target.ownerDocument;

  root=svgDocument.rootElement;
  old_scale = root.currentScale;
  new_scale = old_scale * k;
  root.currentScale = new_scale;

  browserEval ( "document.getElementById('svg_vis').height *= " + k + ";document.getElementById('svg_vis').width  *= " + k );
}

function pan(k1,k2) {
  if ( window.svgDocument == null )
    svgDocument = e.target.ownerDocument;

  root=svgDocument.rootElement;

  if (k1!=0) {
    old_x=root.currentTranslate.x;
    x=old_x+k1*20;root.currentTranslate.x=x;
  } else {
    old_y=root.currentTranslate.y;
    y=old_y+k2*20;root.currentTranslate.y=y;
  }
}

function reset() {
  if ( window.svgDocument == null )
    svgDocument = e.target.ownerDocument;

  root=svgDocument.rootElement;
  root.currentTranslate.x=0;
  root.currentTranslate.y=0;

  var old_scale = root.currentScale;
  root.currentScale=1;

  browserEval ( "document.getElementById('svg_vis').height /= " + old_scale + ";document.getElementById('svg_vis').width  /= " + old_scale );
}

function tape(evt) {
  key = evt.getCharCode();
  switch(key) {
  case 43 : zoomer(2);break;
  case 45 : zoomer(0.5);break;
  case 114: reset();break;
  case 82: reset();break;
  case 50: pan(0,1);break;
  case 52: pan(-1,0);break;
  case 54: pan(1,0);break;
  case 56: pan(0,-1);break;
  }
}

function azap_init(zap) {
  azap.appendNode(zap);

  // This update is need to initialize all mananged nodes
  // Really this is a hack to get around this "feature" of the code
  azap.update();
}

function init ( evt ) {
  var vhooks = document.getElementsByTagName ( "vhook" );

  var sel_rows = "";
  for ( var i = 0; i < vhooks.length; i++ ) {
    sel_rows += vhooks.item(i).getAttribute ( "annot" ) + NL;
  }

  loadGUI ( evt );

  azap = new AntiZoomAndPan();
  azap.appendNode ( document.getElementById ( 'h_tbr' ) );
  azap.appendNode ( document.getElementById ( 'v_tbr' ) );
  azap.update();

  getSVGDoc ( evt );
 
  //  var newMenuRoot = parseXML(printNode(document.getElementById('epng_menu')), contextMenu);
  //  contextMenu.replaceChild( newMenuRoot, contextMenu.firstChild );

  old_scale = svgDocument.rootElement.currentScale;

//  browserEval ( "if ( top.document.mainfrm && top.document.mainfrm.subselect_row_headers___c_15_s_1 ) top.document.mainfrm.subselect_row_headers___c_15_s_1.value='" + sel_rows + "';" );
}
